/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cc.altius.web.controller;

import cc.altius.domain.CustomUserDetails;
import cc.altius.domain.Password;
import cc.altius.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

/**
 *
 * @author Akil Mahimwala
 */
@Controller
@RequestMapping("/home/changePassword.htm")
@SessionAttributes("password")
public class ChangePasswordController {

    @Autowired
    private UserService userService;

    @RequestMapping(method = RequestMethod.GET)
    private String showForm(ModelMap model) {
        Password password = new Password();
        CustomUserDetails curUser = (CustomUserDetails) (SecurityContextHolder.getContext().getAuthentication().getPrincipal());
        password.setUserId(curUser.getUserId());
        password.setUsername(curUser.getUsername());
        model.addAttribute("password", password);
        return "/home/changePassword";
    }

    @RequestMapping(method = RequestMethod.POST)
    private String updatePassword(final @ModelAttribute("password") Password password, Errors errors) {
        if (!this.userService.confirmPassword(password)) {
            //System.out.println("Nested path="+errors.getNestedPath());
            errors.rejectValue("oldPassword","msg.oldPasswordNotMatch");
            return "/home/changePassword";
        } else {
            this.userService.updatePassword(password, 90);
            return "redirect:/home/index.htm?msg=msg.passwordUpdated";
        }
    }
}
